import java.util.Arrays;


public class HuffmanTree {

	private Node root;
	private 
	
	
	public HuffmanTree( Node[] nodes)
	{

		
	}
	
	public Node buildTree(Node[] nodes)
	{
		if ( nodes == null)
		{
			root = new Node( (Character) null);
		}
		else if ( nodes.length == 1)
		{
			root = nodes[0];
		}
		else
		{
			this.root = assemble(nodes)[0];
		}
		return root;
	}
	
	public Node[] assemble(Node[] nodes)
	{
		Arrays.sort(nodes);
		Node parentNode = new Node((Character) null);
		parentNode.setLeft(nodes[0]);
		parentNode.setLeft(nodes[1]);
		parentNode.setOccurances(nodes[0].getOccurances() + nodes[1].getOccurances() );
		parentNode.setLeaf(false);
		Node[] newNodes = new Node[nodes.length - 1];
		newNodes[0] = parentNode;
		for (int i = 2; i < nodes.length ; i++)
		{
			newNodes[i-1] = nodes[i];
		}
		if ( newNodes.length >= 2 )
		{
			return assemble(newNodes);
		}
		return newNodes;
	}

	public Node index(Node start)
	{
		return start;
	}
	
	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}
}
